<template>
  <!-- 只在离线时显示网络状态 -->
  <div v-if="!networkStore.isOnline" class="network-status offline">
    <el-alert
      :title="alertTitle"
      type="warning"
      :closable="false"
      show-icon
    >
      <template #default>
        <div class="offline-info">
          <p>{{ alertMessage }}</p>
          <div class="offline-actions">
            <el-button
              size="small"
              @click="networkStore.attemptReconnect"
              :disabled="!networkStore.canReconnect"
              :loading="isReconnecting"
            >
              {{ reconnectButtonText }}
            </el-button>
            <el-tag size="small" type="info">
              离线记录: {{ networkStore.getOfflineRecordCount() }} 条
            </el-tag>
          </div>
        </div>
      </template>
    </el-alert>
  </div>
</template>

<script setup lang="ts">

import { computed, ref, watch } from 'vue'

import { useNetworkStore } from '../stores/networkStore'

const networkStore = useNetworkStore()
const isReconnecting = ref(false)

// 计算属性
const alertTitle = computed(() => {
  return networkStore.canReconnect ? '网络连接中断' : '网络连接失败'
})

const alertMessage = computed(() => {
  if (networkStore.canReconnect) {
    return `正在尝试重连... (${networkStore.reconnectAttempts}/${networkStore.maxReconnectAttempts})`
  } else {
    return '网络连接失败，请检查网络设置或联系技术支持'
  }
})

const reconnectButtonText = computed(() => {
  if (isReconnecting.value) {
    return '重连中...'
  } else if (networkStore.canReconnect) {
    return '立即重连'
  } else {
    return '重连失败'
  }
})

// 监听重连状态
watch(() => networkStore.reconnectAttempts, (newVal, oldVal) => {
  if (newVal > oldVal) {
    isReconnecting.value = true
    setTimeout(() => {
      isReconnecting.value = false
    }, 2000)
  }
})
</script>

<style scoped>
.network-status.offline {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 9999;
  margin: 0;
}

.offline-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.offline-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}
</style>
